#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/12/27 19:24
# @Author : ZhengQL

import requests
from common.Excel_Handler import ExcelHandler
import time
import os
import socket
from common.Path_Handler import PathHandler


# 给企业微信发送通知
class WXRobot:


    def upload_file(self, key, file_type, file_path, filename):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={key}&type={file_type}"
        files = {
            'media': (filename, open(file_path, 'rb'), 'application/octet-stream')
        }
        response = requests.post(url, files=files)
        media_id = response.json()['media_id']
        return media_id


    def robot_send(self):

        """汇总测试结果、并发送企业微信"""
        all_cases = 0
        success_cases = 0
        fail_cases = 0
        skip_cases = 0
        error_cases = 0

        """获取测试用例总数"""
        excel = ExcelHandler(PathHandler.cases_path + r'\cases.xlsx')
        data = excel.read_excel('Sheet1')
        all_cases = len(data)
        # print(len(data))
        try:
            for i in range(all_cases):
                if data[i]['test_result'] == 'Pass':
                    success_cases += 1
                elif data[i]['test_result'] == 'Fail':
                    fail_cases += 1
                elif data[i]['test_result'] == 'Error':
                    error_cases += 1
        except IndexError as e:
            print(f"IndexError occurred: {e}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")

        # 自动化执行时间
        now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

        # 计算通过率
        pass_rate = round(success_cases / all_cases * 100, 2)

        # 获取文件夹名称
        file_list = sorted(os.listdir(PathHandler.output_path + r'\result')[:])
        print(file_list)
        file_name = file_list[-1]
        print(file_name)

        file_path = os.path.join(PathHandler.output_path + r'\result', file_name)
        print(file_path)

        # 获取本机ip地址
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_IP = s.getsockname()[0]
        print(local_IP)
        s.close()

        # 输出报告地址
        # 拼接网址
        report_url = f"http://{local_IP}:63342/DG_Test/reports/{file_name}?_ijt=isht0cjpgfouq02rhk2vefuhpi&_ij_reload=RELOAD_ON_SAVE"
        # 生成最终的 HTML 字符串
        html_string = f"报告地址：<font color=\"gray\">{report_url}</font> \n"
        # 打印或返回 html_string
        print(html_string)



        # 发送企业微信通知
        headers = {"Content-Type": "text/plain"}
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=1dff9dc1-8c8a-4a65-9676-4c7b0f3b94f5'
        send_data = {
            "msgtype": "markdown",  # 消息类型，此时固定为markdown
            "markdown": {
                "content": "#  **【低空运行管理中心_自动化通知】**<font color=\"warning\"></font>\n" +  # 标题 （支持1至6级标题，注意#与文字中间要有空格）
                           f"> 测试环境：<font color=\"block\">东高UAT环境</font> \n" +  # 字体颜色(只支持3种内置颜色)
                           f"> 测试人员：<font color=\"block\">@小郑</font> \n" +  # 字体颜色(只支持3种内置颜色)
                           f"> > <font color=\"block\"></font> \n" +  # 字体颜色(只支持3种内置颜色)
                           f"#### **执行结果 **\n" +  # 加粗：**需要加粗的字**
                           f"> 时间：<font color=\"block\">{now_time}</font> \n" +  # 字体颜色(只支持3种内置颜色)
                           # "> * 自动化测试 * <font color=\"info\"></font> \n" +  # 引用：> 需要引用的文字
                           f"> **总用例数**：<font color=\"blue\">{all_cases}例</font> \n" +  # 字体颜色(只支持3种内置颜色)
                           f"> 通过用例数：<font color=\"info\">{success_cases}例</font> \n"  # 绿色：info、灰色：comment、橙红：warning
                           f"> 失败用例数：<font color=\"red\">{fail_cases}例</font> \n"  # 绿色：info、灰色：comment、橙红：warning
                           f"> 错误用例数：<font color=\"gray\">{error_cases}例</font> \n"  # 绿色：info、灰色：comment、橙红：warning
                           f"> <font color=\"info\">**通过率：**{pass_rate}%</font> \n"
                           f"> > <font color=\"block\"></font> \n" +  # 字体颜色(只支持3种内置颜色)
                        # 测试报告地址，但是无法通过ip进行访问
                        #    f"> 测试报告地址：<font color=\"gray\">{report_url}</font> \n"  # 绿色：info、灰色：comment、橙红：warning
                        #    f"> > <font color=\"block\"></font> \n" +  # 字体颜色(只支持3种内置颜色)
                           f"> **非相关负责人员可忽略此消息。** <font color=\"block\"></font> \n"  # 字体颜色(只支持3种内置颜色)
            }
        }
        res = requests.post(url=send_url, headers=headers, json=send_data)
        print(res.json())

        # 发送文件到企业微信
        file_path = os.path.join(PathHandler.output_path + r'\result', file_name)
        media_id = self.upload_file('1dff9dc1-8c8a-4a65-9676-4c7b0f3b94f5', 'file', file_path, file_name)
        # print(f'1111111111{media_id}')

        send_data2 = {
            "msgtype": "file",
            "file": {
                "media_id": media_id
            }
        }

        # 但是发送通知放在了后置处理器，所以读取不到最新的文件...
        res2 = requests.post(url=send_url, headers=headers, json=send_data2)
        print(res2.json())




if __name__ == '__main__':
    wx_robot = WXRobot()
    wx_robot.robot_send()

